import { RootThunkAction } from '@/types/store'
import { http } from '@/utils/http'
import { setToken, clearToken } from '@/utils/token'
// import type { Token } from '@/types/data'
import { LoginResponse } from '@/types/data'

//login函数参数类型
type LoginParams = { mobile: string; code: string }
//login接口响应类型
// type LoginResponse = {
// 	message: string
// 	data: Token
// }

//登录action
export const login = (values: LoginParams): RootThunkAction => {
	return async (dispatch) => {
		//发送请求
		const res = await http.post<LoginResponse>('/authorizations', values)
		//拿到返回数据
		const tokens = res.data.data
		//设置本地token
		setToken(tokens)
		//分发action
		dispatch({ type: 'login/token', payload: tokens })
	}
}

//获取验证码
export const getCode = (mobile: string) => {
	return async () => {
		await http.get(`/sms/codes/${mobile}`)
		// 注意：验证码是发送到手机上的，因此，不需要更新Redux状态
	}
}

//退出登录
export const logout = (): RootThunkAction => {
	return async (dispatch) => {
		dispatch({ type: 'login/logout', clearToken })
	}
}
